package com.cat.slidingWindow;

/**
 * @author cat
 * @description https://leetcode.cn/problems/count-subarrays-where-max-element-appears-at-least-k-times/
 * @create 2025/7/30 19:06
 * @since JDK17
 */

public class Solution16 {
    public long countSubarrays(int[] nums, int k) {
        int ans = 0, cnt = 0, max = nums[0], n = nums.length;
        for (int i = 0; i < n; i++) {
            max = Math.max(max, nums[i]);
        }

        for (int l = 0, r = 0; r < n; ) {
            while (r < n && cnt < k) {
                cnt += nums[r++] == max ? 1 : 0;
            }
            while (cnt >= k) {
                cnt += n - r + 1;
                cnt -= nums[l++] == max ? 1 : 0;
            }
        }

        return ans;
    }
}
